package com.atguigu.study.controller;

import com.atguigu.study.entities.User;
import com.atguigu.study.resp.ResultData;
import com.atguigu.study.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {
    @Resource
    private UserService userService;

    @PostMapping(value = "/add")
    public ResultData<Boolean> addUser(@RequestBody User user){
        return ResultData.success(userService.save(user));
    }

    @GetMapping(value = "/{id}")
    public ResultData<User> getUserById(@PathVariable("id") Integer id){
        return ResultData.success(userService.getById(id));
    }

    @PutMapping(value = "/update")
    public boolean update(@RequestBody User user){
        User oldUser = userService.getBaseMapper().selectById(user.getId());
        LambdaUpdateWrapper<User> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper
                .set(User::getUsername,user.getUsername())
                .set(User::getPassword,user.getPassword())
                .set(User::getSex,user.getSex())
                .set(User::getCreateTime,user.getCreateTime())
                .set(User::getVersion,oldUser.getVersion()+1)
                .eq(User::getId,user.getId());
        return userService.update(updateWrapper);


    }

    @GetMapping(value = "/get")
    public User getByUserName(@RequestParam("username") String username) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername, username);
        return userService.getOne(queryWrapper);
    }


    @GetMapping("/selectPage")
    public List<User> selectPage(@RequestParam("pageNum") int pageNum,@RequestParam("pageSize") int pageSize){
        IPage<User> page = new Page(pageNum,pageSize);
        return userService.page(page).getRecords();
    }
}
